package top.xia17.plugins.fast.user.ds;

import cn.hutool.core.util.StrUtil;
import top.xia17.plugins.fast.common.database.dynamic.DsSwitch;
import top.xia17.plugins.fast.common.exceptions.BadConfigException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.xia17.plugins.fast.dynamic.datasource.aop.DynamicSwitchDatasourceAdvisor;
import top.xia17.plugins.fast.user.config.UserProperties;

/**
 * 用户多数据源配置
 * @author xia17
 */
@Configuration
@ConditionalOnClass(DynamicSwitchDatasourceAdvisor.class)
@ConditionalOnBean(DsSwitch.class)
@ConditionalOnProperty(
        prefix = "xia17fast.user",
        name = {"dynamic-datasource-support"},
        havingValue = "true"
)
public class UserDsConfiguration {


    /**
     * 用户使用的数据源切换Aop切面
     * 标记了UserDDS注解的类或者方法将会自动切换至指定数据源
     * @param dsSwitch 多数据源动态切换工具
     * @param userProperties 用户配置
     * @return /
     */
    @Bean
    public DynamicSwitchDatasourceAdvisor dynamicSwitchDatasourceAdvisor(DsSwitch dsSwitch, UserProperties userProperties){
        String ds = userProperties.getDynamicDatasourceName();
        if (StrUtil.isBlank(ds)){
            throw new BadConfigException("开启多数据源支持后,xia17fast-user模块未指定数据源，请配置xia17fast.user.dynamic-datasource-support");
        }
        return new DynamicSwitchDatasourceAdvisor(dsSwitch,ds,UserDDS.class);
    }



}
